﻿using AutoMapper;
using MediatR;
using MES.Process.API.Application.Command.工序命令;
using MES.Process.ErrorCode;
using MES.Process.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace MES.Process.API.Application.CommandHandler.工序命令处理
{
    /// <summary>
    /// 编辑命令处理器
    /// </summary>
    public class ProcessEditCommandHandler : IRequestHandler<ProcessEditCommand, APIResult<int>>
    {
        private readonly ILogger<ProcessEditCommandHandler> _logger;
        private readonly IBaseRepository<Domain.Processes> _processRepository;
        private readonly IMapper mapper;
        public ProcessEditCommandHandler(ILogger<ProcessEditCommandHandler> logger, IBaseRepository<Domain.Processes> processRepository = null, IMapper mapper = null)
        {
            _logger = logger;
            _processRepository = processRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(ProcessEditCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var model = mapper.Map<Domain.Processes>(request);
                if (request.IsUpdOrDel == false)
                {
                    var exists = await _processRepository.GetValues()
                        .AnyAsync(t => t.ProcessCode == request.ProcessCode && t.ID != request.ID, cancellationToken);
                    if (exists)
                    {
                        result.Code = APIEnums.Fail;
                        result.Message = "工序编号已存在";
                        return result;
                    }

                    result.Code = APIEnums.Success;
                    result.Message = "工序编辑成功";
                    _logger.LogInformation("工序编辑成功");
                    result.Data = await _processRepository.UpdateAsync(model);
                    return result;
                }
                else 
                {
                    model.IsDelete = true;
                    result.Code = APIEnums.Success;
                    result.Message = "工序删除成功";
                    result.Data = await _processRepository.UpdateAsync(model);
                    return result;
                }
                
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
